package com.yyw.gulimall.product.exceptions;

import com.yyw.common.exception.FeignCallException;
import com.yyw.common.utils.R;
import com.yyw.common.utils.enums.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class ExceptionControllerAdvice {
    /**
     * 参数校验错误
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R bindingParameter(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        Map<String, String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach(e -> {
            String field = e.getField();
            String message = e.getDefaultMessage();
            map.put(field,message);
        });
        return R.error(ExceptionEnum.BINDING_PARAMETERS.getCode(),ExceptionEnum.BINDING_PARAMETERS.getMsg())
                .put("data",map);
    }

    /**
     * 远程调用Feign失败的异常
     * @param ex
     * @return
     */
    @ExceptionHandler(FeignCallException.class)
    public R feignCallError(FeignCallException ex) {
        return R.error(ExceptionEnum.FEIGN_EXCEPTION.getCode(),ExceptionEnum.FEIGN_EXCEPTION.getMsg())
                .put("data",ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R exceptions(Exception e) {
        log.error("发生了错误",e);
        return R.error(ExceptionEnum.UNKNOW_EXCEPTION.getCode(),ExceptionEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
